<?php
/**
 * Created by PhpStorm.
 * User: 123
 * Date: 2020/9/1
 * Time: 14:34
 */

namespace app\api\controller;


use app\service\MemberService;

use app\service\WxService;
use phpmailer\BaseException;
use think\Controller;
use think\Db;


/**
 * h5微信相关.
 * @author   juzi
 * @blog    https://blog.csdn.net/juziaixiao
 * @version  0.0.1
 * @datetime 2020年7月22日10:57:35
 */
class WeChat extends Controller
{


    private $wxservice;



    /**
     * [__construct 构造方法]
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version  0.0.1
     * @datetime 2020年7月22日10:57:35
     */
    public function __construct()
    {
        // 调用父类前置方法
        parent::__construct();
        $this->wxservice = new WxService(['wechat' => true]);
    }

    /**
     * 从前台获取的url
     * @author   juzi
     * @version 1.0.0
     * @date    2020年4月28日17:12:38
     * @desc    description
     */
    public function SetParam()
    {
        $param = input();
        cache('apiurl', $param['urltag']);
        return json(DataReturn('传输成功', 0));
    }

    /**
     * 微信分享参数.
     * @author   juzi
     * @blog     https://blog.csdn.net/juziaixiao
     * @version  1.0.0
     * @datetime 2020年7月10日09:35:10
     */
    public function Wxconfig()
    {

        $app=$this->wxservice->GetApp();
        $APIs = ['updateAppMessageShareData', 'updateTimelineShareData','getLocation'];
        $app->jssdk->setUrl(input('post.url'));
        $re = $app->jssdk->buildConfig($APIs, false, false, false);
        return json(DataReturn('获取成功', 0, $re));
    }


    /**
     * 微信获取用户授权（获取openid）
     * @author   juzi
     * @version 1.0.0
     * @date    2020年4月28日17:12:38
     * @desc    description
     */
    public function Wxlogin()
    {


        $wxapp = $this->wxservice;
//        $app=$wxapp->GetApp();
        $userinfo = $wxapp->GetAuthSessionKey();
//        $userinfo=$app->user->get($openId);
        //单独查询h5状态
        $h5 = MemberService::MemberInfo('unionid', $userinfo['unionid'], 'id,ish5,headpic,name,phone,openid');
        //h5的openid  为空的时候 修改
        if(empty($h5['openid'])){
            Db::table("member")->where(array('unionid'=>$userinfo['unionid']))->update(array('openid'=>$userinfo['openid']));
        }
        if(empty($h5['headpic'])){
            Db::table("member")->where(array('openid'=>$userinfo['openid']))->update(array(
                'unionid'=>$userinfo['unionid'],
                'headpic'=>$userinfo['headimgurl'],
                'name'=>$userinfo['nickname'],
            ));
        }

        if(empty($h5['phone']))
        {
            //注册
<<<<<<< Updated upstream
            $url='http://test.8a1.top/#/pages/register/register';
           //$url='http://myun.youpilive.com/#/pages/register/register';
=======
//            $url='http://test.8a1.top/#/pages/register/register';
            $url='http://myun.youpilive.com/#/pages/register/register';
>>>>>>> Stashed changes
            header('Location: ' . $url . ((strpos($url, '?') !== false) ? '&' : '?') . '&nickName='.$userinfo['nickname'].'&avatarUrl='.$userinfo['headimgurl'].'&openid='.$userinfo['openid'].'&unionid='.$userinfo['unionid'].'&ish5='.$h5['ish5']);

        }else{
            $AppMemberInfoHandle = new MemberService();
            $token =$AppMemberInfoHandle->AppMemberInfoHandle($h5['id']) ;
            //首页 返回手机号 token
<<<<<<< Updated upstream
            $url='http://test.8a1.top/#/pages/index/index';
            //$url='http://myun.youpilive.com/#/pages/index/index';
=======
//            $url='http://test.8a1.top/#/pages/index/index';
            $url='http://myun.youpilive.com/#/pages/index/index';
>>>>>>> Stashed changes
            header('Location: ' . $url . ((strpos($url, '?') !== false) ? '&' : '?') . '&nickName='.$h5['name'].'&avatarUrl='.$h5['headpic'].'&openid='.$userinfo['openid'].'&unionid='.$userinfo['unionid'].'&ish5='.$h5['ish5'].'&phone='.$h5['phone'].'&token='.$token);
        }

       /* //判断是否存在 不存在在插入
        $member = MemberService::MemberInfo('unionid', $userinfo['unionid'], 'phone,unionid');


        if(empty($member))
        {
            $wxapp->GetUserInfo($openId);
        }

        if(!empty($member['phone']) and strlen(strval($member['phone']))>1)
        {
//            $url='http://myun.youpilive.com/#/pages/index/index';
            $url='http://test.8a1.top/#/pages/index/index';
        }

        $token = MemberService::AppMemberInfoHandle(null, 'openid', $openId);
        #手机号为空跳到注册页
        if(empty($is_h5['phone']))
        {
            $url = cache('apiurl' );
        }
        var_dump($url);exit;
        header('Location: ' . $url . ((strpos($url, '?') !== false) ? '&' : '?') . 'token=' . $token.'&ish5='.$is_h5['ish5'].'&nickName='.$is_h5['name'].'&avatarUrl='.$is_h5['headpic'].'&phone='.$is_h5['phone']);
        exit;*/
    }



     public function LocationInfo(){
        $ak = 'tpandveqFTpYCqKKWu6mS5ITaU3KUm4B';
        $longitude = 113.327782;
        $latitude = 23.137202;
        $result =  getAddressComponent($longitude, $latitude, 1);
        $area=$result['district'];
        dump($result);exit;
      }


    public function getSignPackage() {

        $jsapiTicket = $this->getJsApiTicket();
        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=".strtolower($url);

        $signature = sha1($string);

        $signPackage = array(
            "appId"     => 'wx91063cc93c2cffbf',
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string,
            'JsApiTicket'=>cache('jsapi_ticket')['jsapi_ticket']
        );
        return json($signPackage);
    }

    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    private function getJsApiTicket() {
        // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例

        $accessToken = $this->getAccessToken();

        // 如果是企业号用以下 URL 获取 ticket
        // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
        $data=cache('jsapi_ticket');
        if(empty($data)){
            $res = json_decode($this->httpGet($url));
            $ticket = $res->ticket;
            if ($ticket) {
                $data['expire_time'] = time() + 7000;
                $data['jsapi_ticket'] = $ticket;
                cache('jsapi_ticket',$data);
            }
        }else{
            return $data['jsapi_ticket'];
        }




    }

    private function getAccessToken() {
        // access_token 应该全局存储与更新，以下代码以写入到文件中做示例

        // 如果是企业号用以下URL获取access_token
        // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx91063cc93c2cffbf&secret=65fa6b155ecf70efb8f2346f81b41930";
        $data=cache('access_token');
        if(empty($data)){
            $res = json_decode($this->httpGet($url));
            $access_token = $res->access_token;
            if ($access_token) {
                $data['expire_time'] = time() + 7000;
                $data['access_token'] = $access_token;
                cache('access_token',$data);

            }
        }else{
            return $data['access_token'];
        }

    }

    private function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
        // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }


}